package cn.elead.chaos.remote.web.remote.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.elead.chaos.framework.web.global.ApiResponse;
import cn.elead.chaos.framework.web.global.response.UnifiedReturn;
import cn.elead.chaos.shiro.service.IShiroRealmService;
import cn.elead.chaos.sso.core.user.LoginUser;
import cn.elead.chaos.sso.core.util.SsoUtils;
import cn.elead.chaos.remote.web.remote.domain.SysMenu;
import cn.elead.chaos.remote.web.remote.domain.SysUser;
import cn.elead.chaos.remote.web.remote.domain.vo.RouterVo;
import cn.elead.chaos.remote.web.remote.service.ISysMenuService;
import cn.elead.chaos.remote.web.remote.service.ISysUserService;

/**
 * 登录验证
 * 
 * @author luopeng
 */
@UnifiedReturn
@RestController
public class RemoteLoginController {

	@Autowired
	private IShiroRealmService shiroRealmService;

	@Autowired
	private ISysMenuService menuService;

	@Autowired
	private ISysUserService userService;

	/**
	 * 获取用户信息
	 * 
	 * @return 用户信息
	 */
	@GetMapping("getInfo")
	public ApiResponse<Object> getInfo() {

		Map<String, Object> info = new HashMap<String, Object>();
		LoginUser user = SsoUtils.getUser();
		String userId = user.getUserId();
		// 用户信息
		SysUser sysUser = userService.selectUserById(userId);
		sysUser.setAvatar(user.getAvatar());
		// 角色集合
		Set<String> roles = shiroRealmService.selectRoleKeys(userId);
		// 权限集合
		Set<String> permissions = shiroRealmService.selectPermsByUserId(userId);
		info.put("user", sysUser);
		info.put("roles", roles);
		info.put("permissions", permissions);
		return ApiResponse.<Object>success(info);
	}

	/**
	 * 获取路由信息
	 * 
	 * @return 路由信息
	 */
	@GetMapping("getRouters")
	public List<RouterVo> getRouters() {
		LoginUser user = SsoUtils.getUser();
		List<SysMenu> menus = menuService.selectMenuTreeByUserId(user.getUserId());
		List<RouterVo> buildMenus = menuService.buildMenus(menus);
		return buildMenus;
	}
}
